const { sys_layer_model:SysLayerModel,sys_menu_model: SysMenuModel } = require('../models');
const { Op } = require('sequelize');

class LayerService {
  /**
   * 获取图层列表
   * @param {Object} query 查询条件
   * @returns {Promise<Array>} 图层列表
   */
  async getLayerList(query) {
    const { pageNum = 1, pageSize = 10, layerName, layerType, menuId } = query;
    const where = {
      delFlag: '0'
    };

    if (layerName) {
      where.layerName = {
        [Op.like]: `%${layerName}%`
      };
    }

    if (layerType) {
      where.layerType = layerType;
    }

    if (menuId) {
      where.menuId = menuId;
    }

    const { count, rows } = await SysLayerModel.findAndCountAll({
      where,
      include: [{
        model: SysMenuModel,
        attributes: ['name']
      }],
      order: [['createTime', 'DESC']],
      offset: (pageNum - 1) * pageSize,
      limit: pageSize
    });

    return {
      total: count,
      rows
    };
  }

  /**
   * 获取图层详情
   * @param {number} id 图层ID
   * @returns {Promise<Object>} 图层详情
   */
  async getLayerById(id) {
    return await SysLayerModel.findOne({
      where: {
        id,
        delFlag: '0'
      },
      include: [{
        model: SysMenuModel,
        attributes: ['menuName']
      }]
    });
  }

  /**
   * 创建图层
   * @param {Object} layerData 图层数据
   * @returns {Promise<Object>} 创建的图层
   */
  async createLayer(layerData) {
    return await SysLayerModel.create(layerData);
  }

  /**
   * 更新图层
   * @param {number} id 图层ID
   * @param {Object} layerData 图层数据
   * @returns {Promise<Object>} 更新后的图层
   */
  async updateLayer(id, layerData) {
    await SysLayerModel.update(layerData, {
      where: { id }
    });
    return await this.getLayerById(id);
  }

  /**
   * 删除图层
   * @param {number} id 图层ID
   * @returns {Promise<boolean>} 是否删除成功
   */
  async deleteLayer(id) {
    const result = await SysLayerModel.update(
      { delFlag: '2' },
      { where: { id } }
    );
    return result[0] > 0;
  }

  /**
   * 获取菜单下的图层列表
   * @param {number} menuId 菜单ID
   * @returns {Promise<Array>} 图层列表
   */
  async getLayersByMenuId(menuId) {
    return await SysLayerModel.findAll({
      where: {
        menuId,
        delFlag: '0',
        status: '0'
      },
      order: [['orderNum', 'ASC']]
    });
  }
}

module.exports = new LayerService(); 